<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <!-- @click 点击清空触发事件 -->
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
        @clear="search"
      />
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/enterpriseAdd')"
        >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="enterpriseList"
        @expand-change="expandChange"
      >
        <!-- 拉下列表 -->
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime">
                <template #default="rentObj">
                  {{ rentObj.row.startTime + '至' + rentObj.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="rentObj">
                  <el-tag :type="formatInfoType(scope.row.status)">
                    {{ formatStatus(rentObj.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="rentingOut(scope.row.id)"
                    :disabled="scope.row.status === 3"
                    >退租</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    @click="rentingDel(scope.row.id)"
                    :disabled="scope.row.status !== 3"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="addRent(scope.row.id)"
              v-permission="'park:enterprise:add_edit'"
              >添加合同</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="$router.push(`/enterpriseDetail/${scope.row.id}`)"
              v-permission="'park:enterprise:query'"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="toEditPage(scope.row.id)"
              v-permission="'park:enterprise:add_edit'"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="delEnterprise(scope.row.id)"
              v-permission="'park:enterprise:remove'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加合同 -->
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form
          ref="addForm"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <!--  
              before-upload：上传前的校验
              limit：限制文件的上传个数
              on-exceed：上传文件超出限制时，执行的钩子函数
              on-remove: 移除文件的时候调用
            -->
            <el-upload
              ref="upload"
              action="#"
              :http-request="httpRequest"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="onExceed"
              :on-remove="onRemove"
            >
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >
              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="submit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEnterpriseListAPI,
  delEnterpriseAPI,
  createRentAPI,
  getEnterpriseRentListAPI,
  rentingOutAPI,
  rentingDelAPI
} from '@/api/enterprise'
import { getRentBuildingAPI } from '@/api/building'
import { uploadFile } from '@/api/common'

export default {
  name: 'EnterprisePage',
  data () {
    return {
      params: {
        name: '',
        page: 1,
        pageSize: 10
      },
      enterpriseList: [], // 区域列表数据
      total: 0, // 数据条数
      rentDialogVisible: false, // 显示隐藏弹框
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件', trigger: 'change' }
        ]
      },
      buildingList: []
    }
  },
  created () {
    this.getEnterpriseList()
  },
  methods: {
    // 退租合同
    rentingOut (id) {
      this.$confirm('您确定要退租吗?', '温馨提示').then(async () => {
        await rentingOutAPI(id)
        this.$message.success('退租成功') // 提示
        this.getEnterpriseList() // 重新渲染列表
      })
    },
    // 删除合同
    rentingDel (id) {
      this.$confirm('您确定要删除吗?', '温馨提示').then(async () => {
        await rentingDelAPI(id)
        this.$message.success('删除成功') // 提示
        this.getEnterpriseList() // 重新渲染列表
      })
    },
    // 格式化状态
    formatStatus (status) {
      const statusMap = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '以退租'
      }
      return statusMap[status]
    },
    formatInfoType (status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },
    // 获取企业列表
    async getEnterpriseList () {
      const res = await getEnterpriseListAPI(this.params)
      // console.log('企业列表数据', res.data.rows)
      // 为每一项添加 rentList 收集数据
      this.enterpriseList = res.data.rows.map(item => {
        return {
          ...item,
          rentList: []
        }
      })
      this.total = res.data.total
    },
    // 切换页面
    handleCurrentChange (val) {
      this.params.page = val
      this.getEnterpriseList() // 重新渲染页面
    },
    // 处理序号
    indexMethod (index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    // 点击查询
    search () {
      this.page = 1 // 重置页码为1
      this.getEnterpriseList()
    },
    // 点击编辑跳转页面
    toEditPage (id) {
      // console.log('数据id',id)
      this.$router.push(`/enterpriseAdd?id=${id}`)
    },
    // 删除
    /* 
    1. 绑定事件, 接收参数 id
    2. 绑定提示框
    3. 编写接口函数, 调用接口函数
    */
    delEnterprise (id) {
      this.$confirm('你确定要删除这条数据吗?', '温馨提示')
        .then(async () => {
          await delEnterpriseAPI(id)
          this.$message.success('删除成功')
          if (this.enterpriseList.length === 1 && this.params.page > 1) {
            this.params.page -= 1
          }
          this.getEnterpriseList() // 查询渲染数据
        })
        .catch(() => {})
    },
    // 打开合同
    async addRent (id) {
      this.rentDialogVisible = true
      this.rentForm.enterpriseId = id // 获取企业id
      const res = await getRentBuildingAPI()
      this.buildingList = res.data
    },
    // 关闭弹框
    closeDialog () {
      this.rentDialogVisible = false
      // 清空提示
      this.$refs.addForm.resetFields()
      // 清空表单
      this.rentForm = {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      }
      // 清空上传提示
      this.$refs.upload.clearFiles()
    },
    // 上传文件
    async httpRequest ({ file }) {
      const fd = new FormData()
      fd.append('file', file)
      fd.append('type', 2)
      const res = await uploadFile(fd)
      this.rentForm.contractId = res.data.id // 合同id
      this.rentForm.contractUrl = res.data.url // 合同url
      // 单独校验 上传文件框
      this.$refs.addForm.validateField('contractId')
    },
    // 文件上传前的钩子函数
    beforeUpload (file) {
      // 限制文件类型
      const typeList = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/pdf'
      ]
      const fileType = typeList.includes(file.type) // 文件类似
      const fileSize = file.size / 1024 / 1024 < 5 // 文件大小
      if (fileType && fileSize) {
        return true
      } else {
        this.$message.warning('上传文件不符合要求，请重新上传')
        return false
      }
    },
    // 上传文件超出限制时，执行的钩子函数
    onExceed () {
      this.$message.warning('上传文件个数超出限制,请重新上传')
    },
    // 处理移除文件时，继续显示校验
    onRemove () {
      this.rentForm.contractId = this.rentForm.contractUrl = ''
      this.$refs.addForm.validateField('contractId')
    },
    // 提交合同
    submit () {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          const [startTime, endTime] = this.rentForm.rentTime
          this.rentForm.startTime = startTime
          this.rentForm.endTime = endTime
          delete this.rentForm.rentTime // 删除 rentTime
          await createRentAPI(this.rentForm)
          this.$message.success('添加成功')
          this.getEnterpriseList() // 查询获取企业列表
          this.closeDialog() // 关闭弹框
        }
      })
    },
    // 当用户展开或关闭时都会触发
    // row 是当前展开或者关闭哪一行的数据
    // expandedRows 所有展开行的数据
    async expandChange (row, expandedRows) {
      console.log(row, expandedRows)
      // 判断当前状态是展开还是关闭
      const isInclude = expandedRows.find(item => item.id === row.id)
      if (!isInclude) return
      const res = await getEnterpriseRentListAPI(row.id)
      console.log('下拉数据', res.data)
      // 收集下拉数据
      row.rentList = res.data
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
